package com.alibaba.nacos.naming.core.v2.service;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.pojo.Subscriber;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

public interface ClientOperationService {

    void registerInstance(Service service,
                          Instance instance,
                          String clientId) throws NacosException;

    void deregisterInstance(Service service,
                            Instance instance,
                            String connectId);

    default InstancePublishInfo buildPublishInfo(Instance instance) {
        InstancePublishInfo instancePublishInfo = new InstancePublishInfo().setIp(instance.getIp()).setPort(instance.getPort());

        Map<String, Object> extendDatum = new HashMap<>();
        Optional.ofNullable(instance.getMetadata()).ifPresent(extendDatum::putAll);
        Optional.ofNullable(instance.getInstanceId()).ifPresent(id -> extendDatum.put("customInstanceId", id));
        extendDatum.put("publishInstanceWeight", instance.getWeight());
        extendDatum.put("publishInstanceEnable", instance.isEnabled());
        instancePublishInfo.setExtendDatum(extendDatum);

        instancePublishInfo.setHealthy(instance.isHealthy());
        instancePublishInfo.setCluster(Optional.ofNullable(instance.getClusterName()).orElse("DEFAULT"));
        return instancePublishInfo;
    }

    void subscribeService(Service service,
                          Subscriber subscriber,
                          String connectId);

    void unsubscribeService(Service service,
                          Subscriber subscriber,
                          String connectId);
}
